// ==============================================================================================
// OnDemandTreeNode.cs
//
// Created by: NI, 2007.03.28
// Revised by: NI, 2007.11.23
// ==============================================================================================
using System.Windows.Forms;

namespace RibbonExplorer.Tree
{
  // ==============================================================================================
  /// <summary>
  /// This class represents a tree node that loads its children at the first expansion of the node.
  /// </summary>
  // ==============================================================================================
  public abstract class OnDemandTreeNode : TreeNode
  {
    #region Private fields

    private bool _ChildrenLoaded;

    #endregion

    #region Lifecycle methods

    // --------------------------------------------------------------------------------------------
    /// <summary>
    /// Creates a tree node with the specified name.
    /// </summary>
    /// <param name="text">Name of the tree node.</param>
    // --------------------------------------------------------------------------------------------
    public OnDemandTreeNode(string text)
      : base(text)
    {
      _ChildrenLoaded = false;
      CreateEmptyNode();
    }

    #endregion

    #region Public methods

    // --------------------------------------------------------------------------------------------
    /// <summary>
    /// This method can be called when this tree node is about to expand.
    /// </summary>
    // --------------------------------------------------------------------------------------------
    public void ExpandNode()
    {
      if (!_ChildrenLoaded)
      {
        string oldText = Text;
        try
        {
          Text = "Loading...";
          TreeView.Update();
          OnExpandFirstTime();
        }
        finally
        {
          Text = oldText;
        }
      }
      _ChildrenLoaded = true;
    }

    #endregion

    #region Virtual methods

    // --------------------------------------------------------------------------------------------
    /// <summary>
    /// Override this method to change how an empty child node is created.
    /// </summary>
    // --------------------------------------------------------------------------------------------
    protected virtual void CreateEmptyNode()
    {
      Nodes.Add(new TreeNode("Loading..."));
      Collapse();
    }

    // --------------------------------------------------------------------------------------------
    /// <summary>
    /// Override this method to load the children nodes.
    /// </summary>
    // --------------------------------------------------------------------------------------------
    protected virtual void OnExpandFirstTime()
    {
      Nodes.Clear();
    }

    #endregion
  }
}
